//
//  CUploadPageCtrl.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-19.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CUploadPageCtrl.h"

//===========================================================================================================================

@implementation CUploadPageCtrl

static CUploadPageCtrl *g_Instance = nil;


@synthesize m_Camera;
@synthesize m_Photo;
@synthesize m_PreView;
@synthesize m_ImgPathes;
@synthesize m_strMainImg;
@synthesize m_CameraLoading;

//topbar
@synthesize m_TopBar;

@synthesize m_bIsSketch;

//uploadview
@synthesize m_UploadView;
@synthesize m_Product;

//editview
@synthesize m_EditView;

//addresslist
@synthesize m_AddrLst;
//@synthesize m_Res;

@synthesize m_DraftLst;

//state
@synthesize m_nState;

//activesheet
@synthesize m_Sheet;


+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!g_Instance)
        {
            g_Instance = [super allocWithZone:zone];
        }
    }
    
    return g_Instance;
}

+(CUploadPageCtrl*)DefaultUploadPage
{
    if (!g_Instance)
    {
        g_Instance = [[CUploadPageCtrl alloc] init];
    }
    
    return g_Instance;
}

+(void)DestroyUploadPage
{
    if (g_Instance)
    {
        [g_Instance release];
    }
    
    g_Instance = nil;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    
    m_ImgPathes = [[NSMutableArray array] retain];
    m_bIsSketch = NO;
    m_nState    = 0;
    
    m_CameraLoading = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 32)];
    m_CameraLoading.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    m_CameraLoading.backgroundColor = [UIColor clearColor];
    m_CameraLoading.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:m_CameraLoading];
    [m_CameraLoading release];
    
    m_PreView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 44, 272, self.view.frame.size.height-44)];
    m_PreView.backgroundColor = [UIColor clearColor];
    m_PreView.center = CGPointMake(self.view.frame.size.width/2, m_PreView.center.y);
    m_PreView.userInteractionEnabled = NO;
    m_PreView.hidden = YES;
    [self.view addSubview:m_PreView];
    [m_PreView release];
    
    m_UploadView = [[CUploadView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
    m_UploadView.delegate = self;
    [self.view addSubview:m_UploadView];
    [m_UploadView release];
    
    m_AddrLst = [[CAddressListView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
    //m_AddrLst.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    m_AddrLst.delegate = self;
    [self.view addSubview:m_AddrLst];
    [m_AddrLst release];
    
    /*m_EditView = [[CUploadEditView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height)];
    m_EditView.delegate = self;
    //m_EditView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    [self.view addSubview:m_EditView];
    [m_EditView release];*/
    
    m_DraftLst = [[CDraftList alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height) Size:CGSizeMake(ICON_WIDTH, ICON_HEIGHT)];
    m_DraftLst.delegate = self;
    [self.view addSubview:m_DraftLst];
    [m_DraftLst release];
    
    [self.view bringSubviewToFront:m_UploadView];
    //[self.view bringSubviewToFront:m_EditView];
}

-(void)dealloc
{
    [m_ImgPathes release];
    
    [super dealloc];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//self
-(void)ShowUploadPageCtrl
{
    [self DidShow];
}

-(void)DidShow
{
   if (0 == m_nState)
   {
       if (!m_Sheet)
       {
           m_Sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"相册", nil];
           m_Sheet.actionSheetStyle = UIBarStyleBlackTranslucent;
           
           //check camera
           if (![CameraViewController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
           {
               //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_CameraBtn.enabled = NO;
           }
           else 
           {
               [m_Sheet addButtonWithTitle:@"拍照"];
               //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_CameraBtn.enabled = YES;
           }
           
           //check draft
           if (![self GetSketch:NO])
           {
               //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_DraftBtn.enabled = NO;
           }
           else 
           {
               [m_Sheet addButtonWithTitle:@"草稿"];
               //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_DraftBtn.enabled = YES;
           }
       
           [m_Sheet showInView:[CRootCtrlManager DefaultRootCtrl].view];
           //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_Action = @selector(DidImageSelectorSelected:);
           //[CRootCtrlManager DefaultRootCtrl].m_ImageSelector.m_Target = self;
           //[[CRootCtrlManager DefaultRootCtrl] ShowImageSelector];
       }
   }
}

//activesheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    m_bIsSketch = NO;
    [self SetUploadView];
    
    NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
    
    //album
    if ([title isEqualToString:@"相册"])
    {
        m_Photo = [[PhotosViewController alloc] initWithSize:CGSizeMake(320, 392)];//272, 367
        m_Photo.m_delegate = self;
        m_Photo.m_Target = self;
        m_Photo.m_Action = @selector(DidPhotograph:);
        [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_Photo animated:YES];
        [m_Photo release];
    }
    //camera
    else if ([title isEqualToString:@"拍照"])
    {
        m_Camera = [[CameraViewController alloc] initWithSize:CGSizeMake(320, 392)];//272, 367 248, 359
        m_Camera.m_delegate = self;
        m_Camera.m_Target = self;
        m_Camera.m_Action = @selector(DidPhotograph:);
        [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_Camera animated:YES];
        [m_Camera release];
    }
    //draft
    else if ([title isEqualToString:@"草稿"])
    {
        if ([self GetSketch:YES])
        {
            m_bIsSketch = YES;
            
            /*BOOL bFlag = 0;
            bFlag = (![m_UploadView.m_Name.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_Name.text = nil, NO);
            bFlag = (![m_UploadView.m_ResName.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_ResName.text = nil, bFlag);
            bFlag = (![m_UploadView.m_Addr.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_Addr.text = nil, bFlag);
            
            if (bFlag)
            {
                m_AddrLst.hidden = YES;
                [self ShowUploadView:nil];
                m_AddrLst.center = CGPointMake(self.view.frame.size.width/2, m_AddrLst.center.y);
                m_nState = 1;
            }
            else 
            {
                [self ShowAddressList];
            }*/
            [self ShowDraftList];
        }
        else 
        {
            UIAlertView *fail = [[UIAlertView alloc] initWithTitle:@"错误" message:@"打开草稿失败，请尝试其它方式." delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [fail show];
            [fail autorelease];
        }
    }
    else 
    {
        [self HiddenUploadPageCtrl];
    }
    
    [m_Sheet release];
    m_Sheet = nil;
}

//imageselector
-(void)DidImageSelectorSelected:(id)index
{
    m_bIsSketch = NO;
    
    [self SetUploadView];
    
    //album
    if (0 == [index shortValue])
    {
        m_Photo = [[PhotosViewController alloc] initWithSize:CGSizeMake(320, 360)];//272, 367
        m_Photo.m_Target = self;
        m_Photo.m_Action = @selector(DidPhotograph:);
        [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_Photo animated:YES];
        [m_Photo release];
    }
    //camera
    else if (1 == [index shortValue])
    {
        m_Camera = [[CameraViewController alloc] initWithSize:CGSizeMake(320, 360)];//272, 367 248, 359
        m_Camera.m_Target = self;
        m_Camera.m_Action = @selector(DidPhotograph:);
        [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_Camera animated:YES];
        [m_Camera release];
    }
    //draft
    else if (2 == [index shortValue])
    {
        if ([self GetSketch:YES])
        {
            m_bIsSketch = YES;
            
            BOOL bFlag = 0;
            bFlag = (![m_UploadView.m_Name.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_Name.text = nil, NO);
            bFlag = (![m_UploadView.m_ResName.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_ResName.text = nil, bFlag);
            bFlag = (![m_UploadView.m_Addr.text isEqualToString:@" "]) ? (YES) : (m_UploadView.m_Addr.text = nil, bFlag);
            
            if (bFlag)
            {
                m_AddrLst.hidden = YES;
                [self ShowUploadView:nil];
                m_AddrLst.center = CGPointMake(self.view.frame.size.width/2, m_AddrLst.center.y);
                m_nState = 1;
            }
            else 
            {
                [self ShowAddressList];
            }
        }
        else 
        {
            UIAlertView *fail = [[UIAlertView alloc] initWithTitle:@"错误" message:@"打开草稿失败，请尝试其它方式." delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [fail show];
            [fail autorelease];
        }
    }
    //cancel
    else if (3 == [index shortValue])
    {
        [self HiddenUploadPageCtrl];
    }
    else {;}
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenImageSelector];
}

-(void)HiddenUploadPageCtrl
{
    [UIView beginAnimations:nil context:nil];
    m_EditView.center   = CGPointMake(self.view.frame.size.width+self.view.frame.size.width/2, m_EditView.center.y);
    m_UploadView.center = CGPointMake(self.view.frame.size.width+self.view.frame.size.width/2, m_UploadView.center.y);
    m_AddrLst.center    = CGPointMake(self.view.frame.size.width+self.view.frame.size.width/2, m_AddrLst.center.y);
    [UIView commitAnimations];
    
    [[CRootCtrlManager DefaultRootCtrl] BringCtrlToFront:-1];
}

-(void)DidUploadFinished
{
    m_nState = 0;
    [self HiddenUploadPageCtrl];
}

-(UIImage*)CompressImage:(CGSize)newSize Image:(UIImage*)image
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

///////////////////////////////////////
-(void)Photograph
{
    if (0 == m_nState)
    {
        if ([CameraViewController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            m_Camera = [[CameraViewController alloc] initWithSize:CGSizeMake(280, 405)];
            m_Camera.m_Target = self;
            m_Camera.m_Action = @selector(DidPhotograph:);
            [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:m_Camera animated:YES];
            [m_Camera release];
            
            
        }
        else 
        {
            UIAlertView *nocamera = [[UIAlertView alloc] initWithTitle:@"提示" message:@"抱歉，该设备不支持拍照功能,你可以从相册中选择。" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            nocamera.tag = 2;
            [nocamera show];
            [nocamera autorelease];
        }
    }
}

-(void)DidPhotograph:(UIImage*)image
{
    //m_CameraLoading.text = @"设备关闭中...";
    
    if ([m_ImgPathes count] > 0)
    {
        self.m_PreView.image = image;
        self.m_UploadView.m_Image.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), [m_ImgPathes lastObject]]];
        self.m_UploadView.m_ImgCnt.text = [NSString stringWithFormat:@"%d", [m_ImgPathes count]];
        [self ShowAddressList];
    }
    else 
    {
        [self HiddenUploadPageCtrl];
    }
}

-(void)CImagePickerDidSelectImage:(UIImage *)image
{
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    NSString *path = [[NSString stringWithFormat:@"%d.jpg", [[AppConfig DefaultAppConfig] DateToInt:[[AppConfig DefaultAppConfig] GetTimeFormatString]]] retain];
    [data writeToFile:[NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), path] atomically:YES];
    [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes addObject:path];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    //m_PreView.alpha = 1.0;
    m_PreView.center = CGPointMake(self.view.frame.size.width/2+self.view.frame.size.width, m_PreView.center.y);
    [UIView commitAnimations];
    
    if (5 == [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes count])
    {
        m_Camera.m_PreView.m_TakeAgain.enabled = NO;
        m_Camera.m_PreView.m_TakeAgain.alpha   = 0.5;
    } 
}

-(void)ImagePickerDidSelectImage:(UIImage *)image
{
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    NSString *path = [[NSString stringWithFormat:@"%d.jpg", [[AppConfig DefaultAppConfig] DateToInt:[[AppConfig DefaultAppConfig] GetTimeFormatString]]] retain];
    [data writeToFile:[NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), path] atomically:YES];
    [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes addObject:path];
        
    if (5 == [[CUploadPageCtrl DefaultUploadPage].m_ImgPathes count])
    {
        m_Photo.m_PreView.m_TakeAgain.enabled = NO;
        m_Photo.m_PreView.m_TakeAgain.alpha   = 0.5;
    }
}

-(void)CommitUploadImage:(int)width Height:(int)height Data:(NSData*)data
{
    
    NSString *path = [NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), [m_ImgPathes lastObject]];;
    UIImage *temp = [self CompressImage:CGSizeMake(IMAGE_WIDTH, IMAGE_HEIGHT) Image:[UIImage imageWithContentsOfFile:path]];
    NSData *image = UIImageJPEGRepresentation(temp, 1.0);
    if ([image length] > 81920)
    {
        image = UIImageJPEGRepresentation(temp, 0.9);
    }
    else 
    {
        image = UIImageJPEGRepresentation(temp, 1.0);
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UploadImageResult:) name:MSG_UPLOADIMAGE_RET object:nil];
    
    [[CUser DefaultUser] UserUploadNewProductPic:ICON_WIDTH Height:ICON_HEIGHT Data:image];
}

-(void)UploadImageResult:(NSNotification*)ret
{
    NSLog(@"\r\n\r\n========>上传图片结果:%@\r\n\r\n", ret.object);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADIMAGE_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
    
    if ([ret.object isKindOfClass:[NSDictionary class]])
    {
        if (ret.object)
        {            
            if (!m_Product.P_UrlIcon)
            {
                m_Product.P_UrlIcon  = [ret.object objectForKey:@"thumb"];
                m_Product.P_UrlImage = [ret.object objectForKey:@"big"];
            }
            else 
            {
                m_Product.P_UrlIcon  = [NSString stringWithFormat:@"%@$%@", m_Product.P_UrlIcon, [ret.object objectForKey:@"thumb"]];
                m_Product.P_UrlImage = [NSString stringWithFormat:@"%@$%@", m_Product.P_UrlImage, [ret.object objectForKey:@"big"]];
            }
            NSLog(@"URL:%@\r\n\r\n%@", m_Product.P_UrlIcon, m_Product.P_UrlImage);
            
            //是否已经将所有图片上传完成
            [m_ImgPathes removeLastObject];
            if ([m_ImgPathes count] > 0)
            {
                [self CommitUploadImage:ICON_WIDTH Height:ICON_HEIGHT Data:nil];
            }
            else 
            {
                [self CommitUploadProduct:m_Product.P_UrlImage];
            }
        }
        else
        {
            [m_Product release];
            m_Product = nil;
            
            if (m_UploadView.m_bIsDraft)
            {
                //
            }
            else 
            {
                [self SaveSketch:0];
                [self HiddenUploadPageCtrl];
            }
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
    }
    else 
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"错误" message:ret.object delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [error show];
        [error autorelease];
    }
}

-(void)CommitUploadProduct:(NSString*)ImgPath
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UploadProductResult:) name:MSG_UPLOADPRODUCT_RET object:nil];

    CUser *user = [CUser DefaultUser];
    CAddrInfo *m_Addr = m_UploadView.m_AddrInfo;
    
    //NSArray *iconurls = [m_Product.P_UrlIcon componentsSeparatedByString:@"$"];
    NSArray *imgurls  = [m_Product.P_UrlImage componentsSeparatedByString:@"$"];
    NSMutableString *subimgs = nil;
    if ([imgurls count] > 1)
    {
        subimgs = [NSMutableString string];
        for (int i=1; i<[imgurls count]; i++)
        {
            if (1 == i)
                [subimgs appendFormat:@"%@", [imgurls objectAtIndex:i]];
            else 
                [subimgs appendFormat:@"||%@", [imgurls objectAtIndex:i]];
        }
    }
    
    NSMutableString *request = [NSMutableString string];
    [request appendFormat:@"mobikey=%@", user.U_Token];
    [request appendFormat:@"&sessionid=%@", user.U_Session];
    [request appendFormat:@"&pic_name=%@", m_UploadView.m_Name.text];
    [request appendFormat:@"&pic_path=%@", [imgurls objectAtIndex:0]];
    [request appendFormat:@"&pic_NDYD=%@", subimgs];
    
    [request appendFormat:@"&city=%@", m_Addr.m_strCity];
    [request appendFormat:@"&province=%@", m_Addr.m_strProvince];
    [request appendFormat:@"&country=%@", m_Addr.m_strCountry];
    [request appendFormat:@"&pic_x=%f", m_Addr.m_fX];
    [request appendFormat:@"&pic_y=%f", m_Addr.m_fY];
    
    [request appendFormat:@"&restaurant=%@", m_UploadView.m_ResName.text];
    [request appendFormat:@"&pic_addr=%@", m_UploadView.m_Addr.text];
    [request appendFormat:@"&pic_caption=%@", m_UploadView.m_Sum.text];
    
    [request appendFormat:@"&action=%@", @"addArticle"];
    
    //get infomation of upload
    m_Product.P_Name    = m_UploadView.m_Name.text;
    m_Product.P_City    = m_Addr.m_strCity;
    m_Product.P_ResName = m_UploadView.m_ResName.text;
    m_Product.P_Caption = m_EditView.m_Caption.text;
    m_Product.P_WDu     = [NSNumber numberWithFloat:m_Addr.m_fX];
    m_Product.P_JDu     = [NSNumber numberWithFloat:m_Addr.m_fY];
    
    NSLog(@"\r\n\r\n<========上传美食请求:%@\r\n\r\n", request);
    
    [[CUser DefaultUser] UserUploadNewProduct:request Url:URL_UPLOADPRODUCT Command:UploadP];
}

-(void)UploadProductResult:(NSNotification*)ret
{
    NSDictionary *dic = ret.object;
    
    NSLog(@"\r\n\r\n========>上传美食结果:%@\r\n\r\n", ret.object);

    int nCode = [[dic objectForKey:@"Msg_error"] intValue];
    if (0 == nCode)
    {        
        [CMainPageCtrl DefaultMainPageCtrl].m_NetCnt.m_nLimit += 1;
                
        [m_Product release];
        m_Product = nil;
        [m_ImgPathes removeAllObjects];
        
        //share
        if (m_UploadView.m_nShareType >= 0)
        {
            [self performSelectorOnMainThread:@selector(ShareFood) withObject:nil waitUntilDone:YES];
        }
        
        if (m_UploadView.m_bIsDraft)
        {
            CDraft *draft = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
            if (0 == [draft.m_nSate intValue])
            {
                //
            }
            else 
            {
                //
            }
            
            [m_DraftLst DeleteDraft:draft];
            [m_DraftLst.m_WaterFall InitWaterFall];
            [m_DraftLst AddDraftToList:m_DraftLst.m_Drafts];
            [self HiddenUploadView];
        }
        else 
        {
            [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"temp"];
            [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"temp"];
        }
        
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜，上传成功。" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
        alter.tag = 0;
        [alter show];
        [alter autorelease];
    }
    else 
    {        
        [m_Product release];
        m_Product = nil;
        
        if (!m_UploadView.m_bIsDraft)
        {
            [self SaveSketch:0];
            [self HiddenUploadPageCtrl];
        }
        
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADPRODUCT_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
}

//upload draft
-(void)CommitUploadDraftImage:(int)width Height:(int)height Data:(NSData *)data
{
    NSString *path = [NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), [m_ImgPathes lastObject]];;
    UIImage *temp = [self CompressImage:CGSizeMake(IMAGE_WIDTH, IMAGE_HEIGHT) Image:[UIImage imageWithContentsOfFile:path]];
    NSData *image = UIImageJPEGRepresentation(temp, 1.0);
    if ([image length] > 81920)
    {
        image = UIImageJPEGRepresentation(temp, 0.9);
    }
    else 
    {
        image = UIImageJPEGRepresentation(temp, 1.0);
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UploadImageDraftResult:) name:MSG_UPLOADIMAGE_RET object:nil];
    
    [[CUser DefaultUser] UserUploadNewProductPic:ICON_WIDTH Height:ICON_HEIGHT Data:image];
}

-(void)UploadImageDraftResult:(NSNotification*)ret
{
    NSLog(@"\r\n\r\n========>上传草稿图片结果:%@\r\n\r\n", ret.object);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADIMAGE_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
    
    if ([ret.object isKindOfClass:[NSDictionary class]])
    {
        if (ret.object)
        {
            if (!m_Product.P_UrlIcon)
            {
                m_Product.P_UrlIcon  = [ret.object objectForKey:@"thumb"];
                m_Product.P_UrlImage = [ret.object objectForKey:@"big"];
            }
            else 
            {
                m_Product.P_UrlIcon  = [NSString stringWithFormat:@"%@$%@", m_Product.P_UrlIcon, [ret.object objectForKey:@"thumb"]];
                m_Product.P_UrlImage = [NSString stringWithFormat:@"%@$%@", m_Product.P_UrlImage, [ret.object objectForKey:@"big"]];
            }
            NSLog(@"URL:%@\r\n\r\n%@", m_Product.P_UrlIcon, m_Product.P_UrlImage);
            
            //是否已经将所有图片上传完成
            [m_ImgPathes removeLastObject];
            if ([m_ImgPathes count] > 0)
            {
                [self CommitUploadDraftImage:ICON_WIDTH Height:ICON_HEIGHT Data:nil];
            }
            else 
            {
                [self CommitUploadDraftProduct:m_Product.P_UrlImage];
            }
        }
        else
        {
            [m_Product release];
            m_Product = nil;
            
            [self SaveSketch:0];
            [self HiddenUploadPageCtrl];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
    }
    else 
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"错误" message:ret.object delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [error show];
        [error autorelease];
    }
}

-(void)CommitUploadDraftProduct:(NSString*)ImgPath
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UploadProductDraftResult:) name:MSG_UPLOADPRODUCT_RET object:nil];
    
    CUser *user = [CUser DefaultUser];
    CAddrInfo *m_Addr = m_UploadView.m_AddrInfo;
    
    //NSArray *iconurls = [m_Product.P_UrlIcon componentsSeparatedByString:@"$"];
    NSArray *imgurls  = [m_Product.P_UrlImage componentsSeparatedByString:@"$"];
    NSMutableString *subimgs = nil;
    if ([imgurls count] > 1)
    {
        subimgs = [NSMutableString string];
        for (int i=1; i<[imgurls count]; i++)
        {
            if (1 == i)
                [subimgs appendFormat:@"%@", [imgurls objectAtIndex:i]];
            else 
                [subimgs appendFormat:@"||%@", [imgurls objectAtIndex:i]];
        }
    }
    
    long time = [[AppConfig DefaultAppConfig] DateToInt:[[AppConfig DefaultAppConfig] GetTimeFormatString]];
    NSMutableString *request = [NSMutableString string];
    [request appendFormat:@"mobikey=%@", user.U_Token];
    [request appendFormat:@"&sessionid=%@", user.U_Session];
    [request appendFormat:@"&pic_clientID=%ld", time];
    [request appendFormat:@"&pic_name=%@", m_UploadView.m_Name.text];
    [request appendFormat:@"&pic_path=%@", [imgurls objectAtIndex:0]];
    [request appendFormat:@"&pic_NDYD=%@", subimgs];
    
    [request appendFormat:@"&city=%@", m_Addr.m_strCity];
    [request appendFormat:@"&province=%@", m_Addr.m_strProvince];
    [request appendFormat:@"&country=%@", m_Addr.m_strCountry];
    [request appendFormat:@"&pic_x=%f", m_Addr.m_fX];
    [request appendFormat:@"&pic_y=%f", m_Addr.m_fY];
    
    [request appendFormat:@"&restaurant=%@", m_UploadView.m_ResName.text];
    [request appendFormat:@"&pic_addr=%@", m_UploadView.m_Addr.text];
    [request appendFormat:@"&pic_caption=%@", m_UploadView.m_Sum.text];
    
    [request appendFormat:@"&action=%@", @"upTmp"];
    
    NSLog(@"\r\n\r\n<========上传美食草稿请求:%@\r\n\r\n", request);
    
    [[CUser DefaultUser] UserUploadNewProduct:request Url:URL_UPLOADPRODUCT Command:UploadP];
}

-(void)UploadProductDraftResult:(NSNotification*)ret
{
    NSDictionary *dic = ret.object;
    
    NSLog(@"\r\n\r\n========>上传美食草稿结果:%@\r\n\r\n%@", ret.object, [dic objectForKey:@"Msg"]);
    
    int nCode = [[dic objectForKey:@"Msg_error"] intValue];
    if (0 == nCode)
    {        
        [m_Product release];
        m_Product = nil;
        
        if (!m_UploadView.m_bIsDraft)
        {
            [self SaveSketch:1];
        
            [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"temp"];
            [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"temp"];
        }
        else 
        {
            CDraft *drafts = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
            if (0 == [drafts.m_nSate intValue])
            {
                drafts.m_nSate = [NSNumber numberWithInt:1];
                CKey *key = [[CKey alloc] initWithType:1 Value:drafts.m_nSate Name:@"D_State"];
                [CDraft UpdateDraftInfo:@"Draft" Where:[NSString stringWithFormat:@"D_AID=%ld", [drafts.m_lnID longValue]] Keys:[NSArray arrayWithObjects:key, nil]];
                [key release];
            }
        }
        
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜，保存成功。" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];
        alter.tag = 0;
        [alter show];
        [alter autorelease];
    }
    else 
    {     
        [m_Product release];
        m_Product = nil;
        
        if (!m_UploadView.m_bIsDraft)
        {
            [self SaveSketch:0];
        }
        [self HiddenUploadPageCtrl];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADPRODUCT_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
}

//share
-(void)ShareFood
{
    if (m_UploadView.m_nShareType >= 0)
    {
        //sina
        if (0 == m_UploadView.m_nShareType)
        {
            [self ShareToSina];
        }
        //qq
        else if (1 == m_UploadView.m_nShareType)
        {
            [self ShareToTx];
        }
        else if (2 == m_UploadView.m_nShareType)
        {
            //self.m_PreView.image = nil;
            //[self HiddenUploadPageCtrl];
            [self ShareToRenren];
        }
        else {;}
    }
    
    m_UploadView.m_nShareType = -1;
}

-(void)ShareToSina
{
    [CSinaWeibo DefaultSinawb].m_SinaWeiboDelegate = self;
    [[CSinaWeibo DefaultSinawb] LoginSinaWeibo:[CUploadPageCtrl DefaultUploadPage] Name:[CUser DefaultUser].U_Name];
}

-(void)ShareToTx
{
    [CQWeiBo DefaultQQwb].m_QWeiboDelegate = self;
    [[CQWeiBo DefaultQQwb] LoginQQWeibo:[CUploadPageCtrl DefaultUploadPage] Name:[CUser DefaultUser].U_Name];
}

-(void)ShareToRenren
{
    [CRenren DefaultRenren].delegate = self;
    [[CRenren DefaultRenren] LoginRenren:[CRootCtrlManager DefaultRootCtrl] Name:[CUser DefaultUser].U_Name];
}

-(void)DidLoginRenren:(id)renren State:(int)state
{
    if (0 == state)
    {
        NSString *path = [NSString stringWithFormat:@"%@/tmp/qwb.jpg", NSHomeDirectory()];
        NSData *data = UIImageJPEGRepresentation(m_UploadView.m_Image.image, 1.0);
        [data writeToFile:path atomically:YES];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [[CRenren DefaultRenren] ShareToRenren:m_UploadView.m_Name.text ImageFile:image];
    }
}

-(void)DidLoginSinaWeibo:(CSinaWeibo*)sinaweibo State:(int)state
{
    if (0 == state)
    {
        UIImage *image = m_UploadView.m_Image.image;
        [[CSinaWeibo DefaultSinawb] ShareToSinaWeibo:m_UploadView.m_Name.text ImageFile:image];
    }
}

-(void)DidLoginQQWeibo:(CQWeiBo*)qweibo State:(int)state
{
    if (0 == state)
    {
        NSString *path = [NSString stringWithFormat:@"%@/tmp/qwb.jpg", NSHomeDirectory()];
        NSData   *data = UIImageJPEGRepresentation(m_UploadView.m_Image.image, 1.0);
        [data writeToFile:path atomically:YES];
        [[CQWeiBo DefaultQQwb] ShareToQWeibo:m_UploadView.m_Name.text ImageFile:path];
    }
}

-(void)SetUploadView
{
    m_UploadView.m_AddrInfo.m_strCity     = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
    m_UploadView.m_AddrInfo.m_strProvince = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strProvince];
    m_UploadView.m_AddrInfo.m_strCountry  = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strCountry];
    m_UploadView.m_AddrInfo.m_strSum      = [NSString stringWithFormat:@"%@", [CLocator DefaultLocator].m_AddrInfo.m_strSum];
    m_UploadView.m_AddrInfo.m_fX          = [CLocator DefaultLocator].m_AddrInfo.m_fX;
    m_UploadView.m_AddrInfo.m_fY          = [CLocator DefaultLocator].m_AddrInfo.m_fY;
    
    m_UploadView.m_Name.text    = nil;
    m_UploadView.m_ResName.text = nil;
    m_UploadView.m_Addr.text    = nil;
    m_UploadView.m_Type         = 1;
    
    m_EditView.m_Caption.text = @"想说些什么...";
    m_EditView.m_bIsTx        = NO;
    m_EditView.m_bIsSina      = NO;
    m_EditView.m_Tx.text      = @"断开";
    m_EditView.m_Sina.text    = @"断开";
    
    m_AddrLst.m_ShowStyle   = 2;
}

//uploadview
-(void)DidUploadViewSelected:(int)index View:(CUploadView *)view
{
    [self ShowEditView];
}

//uploadview
-(void)DidUploadViewActived:(UIView *)view Command:(int)command Value1:(id)value1 Value2:(id)value2
{
    //save
    if (0 == command)
    {
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"保存中..."];
        
        if (!m_UploadView.m_bIsDraft)
        {
            m_Product = [[CProduct alloc] init];
            self.m_strMainImg = [m_ImgPathes objectAtIndex:0];
            [self CommitUploadDraftImage:ICON_WIDTH Height:ICON_HEIGHT Data:nil];
        }
        else 
        {
            CDraft *draft = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
            [self SynDraftToServer:draft];
        }
    }
    //drop
    else if (1 == command)
    {
        if (!m_UploadView.m_bIsDraft)
        {
            m_nState = 0;
            [self HiddenUploadPageCtrl];

            m_UploadView.m_Name.text    = nil;
            m_UploadView.m_ResName.text = nil;
            m_UploadView.m_Addr.text    = nil;
        }
        else 
        {
            CDraft *draft = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
            if (1 == [draft.m_nSate intValue])
            {
                [m_DraftLst DeleteNetDrafts:[NSArray arrayWithObjects:draft, nil]];
            }
            [m_DraftLst DeleteDraft:draft];
            [m_DraftLst.m_WaterFall InitWaterFall];
            [m_DraftLst AddDraftToList:m_DraftLst.m_Drafts];
            [self HiddenUploadView];
        }
        
        [m_ImgPathes removeAllObjects];
    }
    //upload
    else if (2 == command)
    {
        if (!m_UploadView.m_bIsDraft)
        {
            if (0 == [m_UploadView.m_Name.text length])
            {
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"美食名称不能为空." delegate:nil cancelButtonTitle:@" 确定" otherButtonTitles:nil];
                [alter show];
                [alter autorelease];
            }
            else 
            {
                [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"上传中..."];
                m_Product = [[CProduct alloc] init];
                [self CommitUploadImage:60 Height:60 Data:nil];
            }   
        }
        else 
        {
            if ([m_UploadView.m_Name.text length] > 0)
            {
                CDraft *draft = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
                if (0 == [draft.m_nSate intValue])
                {
                    //native
                    NSArray *pathes = [[NSFileManager defaultManager] subpathsAtPath:draft.m_strPath];
                    [m_ImgPathes removeAllObjects];
                    for (NSString *str in pathes)
                    { 
                        NSString *name = [str substringFromIndex:[str length]-3];
                        if ([name isEqualToString:@"jpg"])
                        {
                            [m_ImgPathes addObject:name];
                        }
                        [name release];
                    }
                    [m_ImgPathes addObjectsFromArray:pathes];
                    
                    [self CommitUploadImage:ICON_WIDTH Height:ICON_HEIGHT Data:nil];
                }
                else 
                {
                    [self PubTheDraft:draft];
                }
            }
            else 
            {
                UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"美食名称不能为空." delegate:nil cancelButtonTitle:@" 确定" otherButtonTitles:nil];
                [alter show];
                [alter autorelease];
            }
        }
    }
    else {;}
}

-(void)ShowUploadView:(UIImage*)image
{
    if (m_UploadView.center.x > self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidUploadViewShown)];
        m_UploadView.center = CGPointMake(m_UploadView.center.x-m_UploadView.frame.size.width, m_UploadView.center.y);
        [UIView commitAnimations];
    }
}

-(void)DidUploadViewShown
{
    //[m_UploadView.m_Name becomeFirstResponder];
}

-(void)HiddenUploadView
{
    if (m_UploadView.center.x < self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidUploadViewHidden)];
        m_UploadView.center = CGPointMake(m_UploadView.center.x+m_UploadView.frame.size.width, m_UploadView.center.y);
        [UIView commitAnimations];
    }
}

-(void)DidUploadViewHidden
{
    [m_UploadView.m_Addr resignFirstResponder];
    [m_UploadView.m_ResName resignFirstResponder];
    [m_UploadView.m_Name resignFirstResponder];
    m_UploadView.m_nShareType = -1;
    m_UploadView.m_ShareCur.hidden = YES;
    //m_UploadView.m_Image.image = nil;
    m_UploadView.m_Sum.text = nil;
    m_UploadView.m_bIsDraft = NO;
}

//addresslistview
-(void)DidAddressListViewActived:(UIView*)view Command:(int)command Value1:(id)value1 Value2:(id)value2
{
    //添加新内容
    if (0 == [value1 intValue])
    {
        m_UploadView.m_ResName.text = nil;
        m_UploadView.m_Addr.text    = nil;
        
        m_UploadView.m_ResName.enabled = YES;
        //m_UploadView.m_Addr.enabled  = YES;
        m_UploadView.m_AddrBtn.enabled = YES;
        
        [self ShowUploadView:self.m_PreView.image];
    }
    //cancel
    else if (-1 == [value1 intValue])
    {
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.9 Title:@"草稿保存中..."];
        [self SaveSketch:0];
        m_nState = 0;
        if (m_Product)
        {
            [m_Product release];
            m_Product = nil;
        }
        m_PreView.image = nil;
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    else 
    {
        CResInfo *resinfo = value2;
        //设置美食信息
        m_UploadView.m_AddrInfo.m_fX = resinfo.m_fLat;
        m_UploadView.m_AddrInfo.m_fY = resinfo.m_fLon;
        
        m_UploadView.m_ResName.text = resinfo.m_strName;
        m_UploadView.m_Addr.text    = resinfo.m_strVici;
        
        m_UploadView.m_ResName.enabled = NO;
        //m_UploadView.m_Addr.enabled  = NO;
        m_UploadView.m_AddrBtn.enabled = NO;
        
        [self ShowUploadView:self.m_PreView.image];
    }
}

-(void)ShowAddressList
{
    if (m_AddrLst.center.x > self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidShowAddressList)];
        m_AddrLst.center = CGPointMake(m_AddrLst.center.x-m_AddrLst.frame.size.width, m_AddrLst.center.y);
        m_nState = 1;
        [UIView commitAnimations];
    }
    else 
    {
        [self DidShowAddressList];
    }
}

-(void)DidShowAddressList
{
    [m_UploadView.m_Name resignFirstResponder];
    
    [m_AddrLst LoadPositions];
}

-(void)HiddenAddressList
{
    if (m_AddrLst.center.x < self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        //[UIView setAnimationDelegate:self];
        //[UIView setAnimationDidStopSelector:@selector(DidHiddenAddressList)];
        m_AddrLst.center = CGPointMake(m_AddrLst.center.x+m_AddrLst.frame.size.width, m_AddrLst.center.y);
        m_nState = 0;
        [UIView commitAnimations];
    }
}

-(void)DidHiddenAddressList
{
    [m_UploadView.m_Name becomeFirstResponder];
}

//draft list
-(void)ShowDraftList
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(DidShowDraftList)];
    m_DraftLst.center = CGPointMake(self.view.frame.size.width/2, m_DraftLst.center.y);
    m_nState = 1;
    [UIView commitAnimations];
}

-(void)DidShowDraftList
{
    [self.m_DraftLst GetNativeDrafts];
}

-(void)HiddenDraftList
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(DidHiddenDraftList)];
    m_DraftLst.center = CGPointMake(self.view.frame.size.width/2+self.view.frame.size.width, m_DraftLst.center.y);
    m_nState = 0;
    [UIView commitAnimations];
}

-(void)DidHiddenDraftList
{
    [m_DraftLst CancelTask];
    [m_DraftLst.m_WaterFall InitWaterFall];
    m_DraftLst.m_DelBtn.hidden = YES;
    [m_DraftLst.m_Drafts removeAllObjects];
    m_DraftLst.m_NativeCnt.m_nOffset = 0;
    m_DraftLst.m_NativeCnt.m_nLimit  = 9;
    m_DraftLst.m_NetCnt.m_nOffset = 0;
    m_DraftLst.m_NetCnt.m_nLimit  = 9;
}

-(void)DidDraftListClicked:(int)index
{
    //back
    if (0 == index)
    {
        [self HiddenDraftList];
    }
}


-(void)PubTheDraft:(CDraft*)draft
{
    [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"发布中..."];
    
    NSMutableString *request = [NSMutableString string];
    [request appendFormat:@"mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    [request appendFormat:@"&action=%@", @"setTmp"];
    [request appendFormat:@"&tmpID=%ld", [draft.m_lnTID longValue]];
    
    NSLog(@"发布网络草稿:%@", request);
    
    [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_GET_DRAFTS Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:0] MType:Post UserInfo:nil];
}

-(void)SynDraftToServer:(CDraft*)draft
{   
    NSMutableString *request = [NSMutableString string];
    [request appendFormat:@"mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    [request appendFormat:@"&p_id=%ld", [draft.m_lnTID longValue]];
    [request appendFormat:@"&p_name=%@", draft.m_strName];
    [request appendFormat:@"&p_big=%@", draft.m_strMainImgUrl];
    [request appendFormat:@"&p_NDYD=%@", @""];
    [request appendFormat:@"&p_caption=%@", m_UploadView.m_Sum.text];
    [request appendFormat:@"&p_addr=%@", m_UploadView.m_Addr.text];
    [request appendFormat:@"&city=%@", m_UploadView.m_AddrInfo.m_strCity];
    [request appendFormat:@"&province=%@", m_UploadView.m_AddrInfo.m_strProvince];
    [request appendFormat:@"&country=%@", m_UploadView.m_AddrInfo.m_strCountry];
    [request appendFormat:@"&pic_x=%f", m_UploadView.m_AddrInfo.m_fX];
    [request appendFormat:@"&pic_y=%f", m_UploadView.m_AddrInfo.m_fY];
    [request appendFormat:@"&p_restaurant=%@", m_UploadView.m_ResName.text];
    [request appendFormat:@"&pic_caption=%@", m_UploadView.m_Sum.text];
    [request appendFormat:@"&action=%@", @"editTmp"];
    
    draft.m_strName = m_UploadView.m_Name.text;
    draft.m_strResName = m_UploadView.m_ResName.text;
    draft.m_strAddr = m_UploadView.m_Addr.text;
    draft.m_strSum = m_UploadView.m_Sum.text;
    draft.m_strCity = m_UploadView.m_AddrInfo.m_strCity;
    draft.m_strProvince = m_UploadView.m_AddrInfo.m_strProvince;
    draft.m_strCountry = m_UploadView.m_AddrInfo.m_strCountry;
    draft.m_nY = [NSNumber numberWithFloat:m_UploadView.m_AddrInfo.m_fY];
    draft.m_nX = [NSNumber numberWithFloat:m_UploadView.m_AddrInfo.m_fX];
    
    NSMutableArray *keys = [NSMutableArray array];
    CKey *key = [[CKey alloc] initWithType:3 Value:draft.m_strName Name:@"D_Name"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strResName Name:@"D_ResName"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strAddr Name:@"D_Addr"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strSum Name:@"D_Sum"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strCity Name:@"D_City"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strProvince Name:@"D_Province"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:3 Value:draft.m_strCountry Name:@"D_Country"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:draft.m_nX Name:@"D_X"];
    [keys addObject:key];
    [key release];
    
    key = [[CKey alloc] initWithType:2 Value:draft.m_nY Name:@"D_Y"];
    [keys addObject:key];
    [key release];
    
    [CDraft UpdateDraftInfo:@"Draft" Where:[NSString stringWithFormat:@"D_AID=%ld", [draft.m_lnID longValue]] Keys:keys];
    
    NSLog(@"修改草稿：%@", request);
    
    [[CDownLoadManager DefaultDownLoadManager] AddTask:URL_GET_DRAFTS Sponsor:self PostData:[request dataUsingEncoding:NSUTF8StringEncoding] TimeOut:30 Data:[NSNumber numberWithInt:1] MType:Post UserInfo:nil];
}

-(void)CancelDrafts:(NSArray*)drafts
{
    //
}

//operate delegate
-(void)DidOperationFinished:(COperation*)op Data:(NSData*)data Other:(id)other UserInfo:(id)userinfo
{
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic  = [json JSONValue];
    NSLog(@"%@", [dic objectForKey:@"Msg"]);
    
    if (dic)
    {
        int ncode = [other intValue];
        
        //发布网络草稿
        if (0 == ncode)
        {
            CDraft *draft = [m_DraftLst.m_Drafts objectAtIndex:m_DraftLst.m_nSelDraft];
            [m_DraftLst DeleteDraft:draft];
            [m_DraftLst.m_WaterFall InitWaterFall];
            [m_DraftLst AddDraftToList:m_DraftLst.m_Drafts];
            [self performSelectorOnMainThread:@selector(ShareFood) withObject:nil waitUntilDone:YES];
            [self HiddenUploadView];
        }
        //修改网络草稿
        else if (1 == ncode)
        {
            //
        }
    }
    
    [json release];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidOperationError:(COperation*)op Error:(NSError*)error Other:(id)other UserInfo:(id)userinfo
{
    int ncode = [other intValue];
    
    //发布网络草稿
    if (0 == ncode)
    {
        //
    }
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidOperationTimeOut:(COperation*)op Other:(id)other UserInfo:(id)userinfo
{
    int ncode = [other intValue];
    
    //发布网络草稿
    if (0 == ncode)
    {
        //
    }
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

//editview
-(void)DidUploadEditViewActived:(UIView *)view Command:(int)command Value1:(id)value1 Value2:(id)value2
{
    //save
    if (0 == command)
    {
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.9 Title:@"草稿保存中..."];
        [self HiddenEditView:command];
        [self SaveSketch:0];
        m_nState = 0;
        [m_Product release];
        m_Product = nil;
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    //upload
    else if (1 == command)
    {
        if (m_PreView.image)
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.9 Title:@"上传中，请等待..."];
            
            UIImage *temp = [self CompressImage:CGSizeMake(320, 360) Image:nil];
            NSData *data = UIImageJPEGRepresentation(temp, 1.0);
            if ([data length] > 81920)
            {
                data = UIImageJPEGRepresentation(temp, 0.9);
                NSLog(@"size of image:%d", [data length]);
            }
            else 
            {
                data = UIImageJPEGRepresentation(temp, 1.0);
                NSLog(@"size of image:%d", [data length]);
            }
            
            [self CommitUploadImage:60 Height:60 Data:data];
            
            [self HiddenEditView:command];
        }
        else
        {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"美食图片不能为空" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alter show];
            [alter autorelease];
        }
    }
    //hidden
    else if (2 == command)
    {
        [self HiddenEditView:2];
    }
    else {;}
}

-(void)ShowEditView
{
    if (!m_Product)
        m_Product = [[CProduct alloc] init];
    
    if (m_EditView.center.x > self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidEditViewShown)];
        m_EditView.center = CGPointMake(m_EditView.center.x-m_EditView.frame.size.width, m_EditView.center.y);
        [UIView commitAnimations];
    }
    else 
    {
        [self DidEditViewShown];
    }
}

-(void)DidEditViewShown
{
    [m_UploadView.m_ResName resignFirstResponder];
    [m_UploadView.m_Addr resignFirstResponder];
    [m_UploadView.m_Name resignFirstResponder];
}

-(void)HiddenEditView:(int)state
{
    if (m_EditView.center.x < self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        m_EditView.center = CGPointMake(m_EditView.center.x+m_EditView.frame.size.width, m_EditView.center.y);
        [UIView commitAnimations];
    }
    
    [self performSelector:@selector(DidEditViewHidden:) withObject:[NSNumber numberWithInt:state] afterDelay:0.5];
}

-(void)DidEditViewHidden:(NSNumber*)state
{
    //upload
    if (1 == [state intValue])
    {
        [self HiddenUploadView];
    }
    //return
    else if (2 == [state intValue])
    {
        [m_UploadView.m_Name becomeFirstResponder];
    }
    //save
    else 
    {
        [self HiddenUploadView];
    }
}

//draft
-(void)SaveSketch:(int)state
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *name = nil;
    NSString *cont = nil;
    NSString *resn = nil;
    NSString *addr = nil;
    
    if ([m_UploadView.m_Name.text length] <= 0 || !m_UploadView.m_Name.text)
    {
        name = [NSString stringWithString:@""];
    }
    else 
    {
        name = [NSString stringWithString:m_UploadView.m_Name.text];
    }
    
    if ([m_UploadView.m_ResName.text length] <= 0 || !m_UploadView.m_ResName.text)
    {
        resn = [NSString stringWithString:@""];
    }
    else 
    {
        resn = [NSString stringWithString:m_UploadView.m_ResName.text];
    }
    
    if ([m_UploadView.m_Addr.text length] <= 0 || !m_UploadView.m_Addr.text)
    {
        addr = [NSString stringWithString:@""];
    }
    else 
    {
        addr = [NSString stringWithString:m_UploadView.m_Addr.text];
    }
    
    if ([m_UploadView.m_Sum.text length] <= 0 || !m_EditView.m_Caption.text)
    {
        cont = [NSString stringWithString:@""];
    }
    else 
    {
        cont = [NSString stringWithString:m_UploadView.m_Sum.text];
    }
     
    //创建草稿的根目录
    long time = [[AppConfig DefaultAppConfig] DateToInt:[[AppConfig DefaultAppConfig] GetTimeFormatString]];
    if ([[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents/Draft" SubPath:[NSString stringWithFormat:@"%ld", time]])
    {
        //存放图片
        NSString *path = nil;
        NSString *despath = nil;
  
        NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/Documents/temp", NSHomeDirectory()] error:nil];
        for (NSString *file in files)
        {
            path = [NSString stringWithFormat:@"%@/Documents/temp/%@", NSHomeDirectory(), file];
            despath = [NSString stringWithFormat:@"%@/Documents/Draft/%ld/%@", NSHomeDirectory(), time, file];
            [[NSFileManager defaultManager] moveItemAtPath:path toPath:despath error:nil];
            [[AppConfig DefaultAppConfig] RemoveFile:path];
        }
        
        CDraft *draf = [[CDraft alloc] init];
        draf.m_lnID = [NSNumber numberWithLong:time];
        draf.m_lnTID = [NSNumber numberWithInt:0];
        draf.m_nSate= [NSNumber numberWithInt:state];
        draf.m_strName = m_UploadView.m_Name.text;
        draf.m_strResName = m_UploadView.m_ResName.text;
        draf.m_strAddr = m_UploadView.m_Addr.text;
        draf.m_strSum = m_UploadView.m_Sum.text;
        draf.m_strCity = m_UploadView.m_AddrInfo.m_strCity;
        draf.m_strProvince = m_UploadView.m_AddrInfo.m_strProvince;
        draf.m_strCountry = m_UploadView.m_AddrInfo.m_strCountry;
        draf.m_nX = [NSNumber numberWithFloat:m_UploadView.m_AddrInfo.m_fX];
        draf.m_nY = [NSNumber numberWithFloat:m_UploadView.m_AddrInfo.m_fY];
        draf.m_strPath = [NSString stringWithFormat:@"%@/Documents/Draft/%ld", NSHomeDirectory(), time];
        draf.m_strMainImgUrl = nil;
        draf.m_strMainImgPath= [NSString stringWithFormat:@"%@/%@", draf.m_strPath, self.m_strMainImg];
        
        [draf SaveDraft:@"Draft"];
        [draf release];
    }
    else 
    {
        NSLog(@"创建草稿%ld失败。", time);
        [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"temp"];
        [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"temp"];
    }
    
    self.m_strMainImg = nil;
    [m_ImgPathes removeAllObjects];
    
    [pool release];
}

-(BOOL)GetSketch:(BOOL)isread
{
    NSArray *rets = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/Documents/Draft", NSHomeDirectory()] error:nil];    
    
    if ([rets count] > 0)
    {
        if (isread)
        {
            //[m_ImgPathes addObjectsFromArray:rets];
            
            /*NSDictionary *infodic = [[NSDictionary alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@_sketch.dat", [AppConfig DefaultAppConfig].m_DraftPath, [CUser DefaultUser].U_Name]];
            
            if (infodic)
            {
                NSLog(@"\r\n\r\n草稿内容:%@\r\n\rn", infodic);
                
                //设置美食信息
                m_UploadView.m_AddrInfo.m_strCity     = [infodic objectForKey:@"City"];
                m_UploadView.m_AddrInfo.m_strProvince = [infodic objectForKey:@"Province"];
                m_UploadView.m_AddrInfo.m_strCountry  = [infodic objectForKey:@"Country"];
                m_UploadView.m_AddrInfo.m_fX          = [[infodic objectForKey:@"X"] floatValue];
                m_UploadView.m_AddrInfo.m_fY          = [[infodic objectForKey:@"Y"] floatValue];

                m_UploadView.m_Name.text     = [infodic objectForKey:@"Name"];
                m_UploadView.m_ResName.text  = [infodic objectForKey:@"ResName"];
                m_UploadView.m_Addr.text     = [infodic objectForKey:@"Addr"];
                m_EditView.m_Caption.text    = [infodic objectForKey:@"Content"];
                if ([m_EditView.m_Caption.text isEqualToString:@" "])
                {
                    m_EditView.m_Caption.text = nil;
                }
            }
                    
            [infodic release];*/
        }
        
        return YES;
    }
    
    return NO;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //上传成功
    if (0 == alertView.tag)
    {
        [self HiddenAddressList];
        [self HiddenUploadView];
        [self HiddenUploadPageCtrl];
        //分享
        //[self ShareFood];
    }
    //图片上传失败(不覆盖)
    else if (1 == alertView.tag)
    {
        //保存
        if (1 == buttonIndex)
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"草稿保存中..."];
            [self HiddenEditView:0];
            [self SaveSketch:0];
            m_bIsSketch = NO;
            [m_Product release];
            m_Product = nil;
        }
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    //图片上传失败(覆盖)
    else if (2 == alertView.tag)
    {
        //覆盖
        if (1 == buttonIndex)
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"草稿覆盖中..."];
            [self HiddenEditView:0];
            [self SaveSketch:0];
            m_bIsSketch = NO;
            [m_Product release];
            m_Product = nil;
        }
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    else {;}
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)RequestError:(NSNotification*)mes
{
    //NSError *error = (NSError*)mes.object;
    //NSLog(@"Error:%@(%d)", error.domain, error.code);
    UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示" message:@"操作超时，稍后再试。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [error show];
    [error autorelease];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADPRODUCT_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADIMAGE_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
    
    [[CRootCtrlManager DefaultRootCtrl] SetLoadViewTitle:@"草稿保存中..."];
    [self SaveSketch:0];

    //[self performSelectorOnMainThread:@selector(SetUploadView) withObject:nil waitUntilDone:YES];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)RequestTimeOut:(NSNotification*)mes
{
    //NSError *error = (NSError*)mes.object;
    //NSLog(@"TimeOut:%@(%d)", error.domain, error.code);
    UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示" message:@"操作超时，稍后再试。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [error show];
    [error autorelease];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADPRODUCT_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_UPLOADIMAGE_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
    
    [[CRootCtrlManager DefaultRootCtrl] SetLoadViewTitle:@"草稿保存中..."];
    [self SaveSketch:0];
    
    //[self performSelectorOnMainThread:@selector(SetUploadView) withObject:nil waitUntilDone:YES];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

@end
